const WebSocket = require('ws');
const http = require('http');

// 创建HTTP服务器（WebSocket依赖）
const server = http.createServer();
server.listen(8080, '0.0.0.0', () => {
    console.log('Server running on http://localhost:8080');
});

// 创建WebSocket服务器
const wss = new WebSocket.Server({ server });

// 存储已连接用户（userId: WebSocket）
const users = new Map();

// 广播消息给所有用户（除发送者）
function broadcast(data, senderWs) {
    console.log('users:', users.size)

    wss.clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) { //client !== senderWs && 
            client.send(data);
        }
    });
}

wss.on('connection', (ws) => {
    const { remoteAddress, remotePort } = ws._socket;
    console.log(`[新连接] ${remoteAddress}:${remotePort}`);

    // 广播在线人数
    broadcast(JSON.stringify({
        type: 'other',
        users: users.size
    }), ws);

    let userId = null;

    // 接收客户端消息
    ws.on('message', (message) => {
        const receivedMsg = message.toString();

        if (!userId) {
            // 首次消息视为用户ID注册
            if (users.has(receivedMsg)) {
                ws.send(JSON.stringify({
                    type: 'error',
                    message: 'User ID already exists'
                }));
                // ws.close();
                return;
            }

            userId = receivedMsg;
            users.set(userId, ws);
            console.log(`[注册] ${userId}用户注册，(${ws._socket.remoteAddress})`);

            // 广播系统消息
            broadcast(JSON.stringify({
                type: 'system',
                message: `${userId} 加入聊天`,
                users: users.size
            }), ws);

        } else {
            // 普通聊天消息处理
            console.log(`[${userId}(${ws._socket.remoteAddress})] ${receivedMsg}`);
            broadcast(JSON.stringify({
                type: 'message',
                userId,
                message: receivedMsg,
                timestamp: new Date().toISOString(),
                users: users.size

            }), ws);
        }
    });

    // 客户端断开连接处理
    ws.on('close', () => {
        if (userId) {
            users.delete(userId);
            console.log(`[断开连接] ${userId}`);
            broadcast(JSON.stringify({
                type: 'system',
                message: `${userId} 离开聊天`,
                users: users.size
            }));
        }
    });

    // 错误处理
    ws.on('error', (error) => {
        console.error(`WebSocket error: ${error}`);
    });
});

console.log('WebSocket server listening on ws://0.0.0.0:8080');